package com.drcoffee.drcoffeemall.service.impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayConfig;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayDataDataserviceBillDownloadurlQueryModel;
import com.alipay.api.request.AlipayDataDataserviceBillDownloadurlQueryRequest;
import com.alipay.api.response.AlipayDataDataserviceBillDownloadurlQueryResponse;
import com.drcoffee.drcoffeemall.entry.FileEntity;
import com.drcoffee.drcoffeemall.entry.Result;
import com.drcoffee.drcoffeemall.entry.WxBill;
import com.drcoffee.drcoffeemall.mapper.WxBillMapper;
import com.drcoffee.drcoffeemall.service.WxBillService;
import com.wechat.pay.java.core.Config;
import com.wechat.pay.java.core.RSAAutoCertificateConfig;
import com.wechat.pay.java.service.billdownload.BillDownloadServiceExtension;
import com.wechat.pay.java.service.billdownload.DigestBillEntity;
import com.wechat.pay.java.service.billdownload.model.BillType;
import com.wechat.pay.java.service.billdownload.model.GetTradeBillRequest;
import com.wechat.pay.java.service.billdownload.model.TarType;
import lombok.extern.slf4j.Slf4j;
import org.mozilla.universalchardet.UniversalDetector;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service
@Slf4j
public class WxBillServiceImpl implements WxBillService {

    @Autowired
    WxBillMapper wxBillMapper;

    /**
     * app_id
     */
    @Value("${wechat.app_id}")
    private String app_id;

    /**
     * 商户号
     */
    @Value("${wechat.merchantId}")
    private String merchantId = "1489444742";

    /**
     * 商户API私钥路径
     */
    @Value("${wechat.privateKeyPath}")
    private String privateKeyPath;

    /**
     * 商户证书序列号
     */
    @Value("${wechat.merchantSerialNumber}")
    private String merchantSerialNumber;

    /**
     * 商户APIV3密钥
     */
    @Value("${wechat.apiV3Key}")
    private String apiV3Key;


    /**
     * ==============================支付宝支付手续费配置=====================================
     * @return
     */
    /**
     * APPID，收款账号既是您的APPID对应支付宝账号
     */
    @Value("${alipay.app_id}")
    private String app_id1;

    /**
     * 商户私钥，PKCS8格式RSA2私钥
     */
    @Value("${alipay.merchant_private_key}")
    private String merchant_private_key;

    /**
     * 支付宝公钥
     */
    @Value("${alipay.alipay_public_key}")
    private String alipay_public_key;


    /**
     * 签名方式
     */
    @Value("${alipay.sign_type}")
    private String sign_type;

    /**
     * 字符编码格式
     */
    @Value("${alipay.charset}")
    private String charset;

    /**
     * 支付宝网关
     */
    @Value("${alipay.gateway_url}")
    private String gateway_url;



    @Scheduled(cron = "0 30 10 * * ?")
    public Result getData(){
        LocalDate currentDate = LocalDate.now();
        LocalDate yesterday = currentDate.minusDays(1);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String formattedDate = yesterday.format(formatter);

        try {
            log.info("=============== 获取微信交易记录 ==============");
            Config config =
                    new RSAAutoCertificateConfig.Builder()
                            .merchantId(merchantId)
                            .privateKeyFromPath(privateKeyPath)
                            .merchantSerialNumber(merchantSerialNumber)
                            .apiV3Key(apiV3Key)
                            .build();
            BillDownloadServiceExtension service = new BillDownloadServiceExtension.Builder().config(config).build();
            GetTradeBillRequest request = new GetTradeBillRequest();
            request.setBillDate("2024-04-02");
//            request.setBillDate(formattedDate);
            request.setBillType(BillType.ALL);
            request.setTarType(TarType.GZIP);
            DigestBillEntity bill = service.getTradeBill(request);

            FileEntity fileEntity = new FileEntity();
            try (InputStream inputStream = bill.getInputStream()) {
                try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
                    byte[] buffer = new byte[16384];
                    int bytesRead;
                    while ((bytesRead = inputStream.read(buffer)) != -1) {
                        outputStream.write(buffer, 0, bytesRead);
                    }
                    fileEntity.setFileContent(outputStream.toByteArray());
                }
            }
            String jsonContent = new String(fileEntity.getFileContent());
            String[] parts=jsonContent.split(",");
            List<String> list = new ArrayList<>(Arrays.asList(parts));
            System.out.println("微信支付账单记录****************************"+list);
            // 获取倒数第七个索引的值
            int index = list.size() - 7;
            if (index >= 0 && index < list.size()) {
                String value = list.get(index);
                char ss = value.charAt(value.length() - 1);
                Integer sy = Integer.parseInt(String.valueOf(ss));
                for (int s=0; s<=sy-1 ;s++){
                    WxBill wxBill = new WxBill();
                    wxBill.setOdd(list.get(31+s*26).substring(1));
                    wxBill.setBCharges(list.get(48+s*26).substring(1));
                    if (wxBill!=null){
                        //this.insertW(wxBill);
                    }
                }
            } else {
                System.out.println("列表长度不足，无法获取倒数第四个索引的值。");
            }
            System.out.println("55555555555555555555555555555555555"+list);
            return new Result(1, "SUCCESS", "", bill);
        } catch (Exception e) {
            log.error("Exception", e);
            return new Result(-1, "ERROR", e.getMessage(), null);
        }
    }


    @Scheduled(cron = "0 0 11 * * ?")
    @Override
    public void tRecord() {
        List<String> all = this.getAll();
        for (String s : all) {
            String result = this.selectW(s);
            if (result != null) {
                this.updateTrade(s, result.substring(0, 4));
            }
        }
    }

    @Override
    public List<String> getAll() {
        return wxBillMapper.getAll();
    }

    @Override
    public void updateTrade(String tradeNo, String trade_BCharges) {
        wxBillMapper.updateTrade(tradeNo, trade_BCharges);
    }

    @Override
    public void insertW(WxBill wxBill) {
        wxBillMapper.insertW(wxBill);
    }

    @Override
    public String selectW(String odd) {
        return wxBillMapper.selectW(odd);
    }

    /**
     * 支付宝支付手续费查询
     * @param
     * @return
     */
    public Result aliPay() {
        try{
            String privateKey = merchant_private_key;
            String alipayPublicKey = alipay_public_key;
            AlipayConfig alipayConfig = new AlipayConfig();
            alipayConfig.setServerUrl("https://openapi.alipay.com/gateway.do");
            alipayConfig.setAppId(app_id1);
            alipayConfig.setPrivateKey(privateKey);
            alipayConfig.setFormat("json");
            alipayConfig.setAlipayPublicKey(alipayPublicKey);
            //alipayConfig.setCharset("GBK");
            alipayConfig.setSignType("RSA2");
            AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig);
            AlipayDataDataserviceBillDownloadurlQueryRequest request = new AlipayDataDataserviceBillDownloadurlQueryRequest();
            AlipayDataDataserviceBillDownloadurlQueryModel model = new AlipayDataDataserviceBillDownloadurlQueryModel();
            //model.setSmid("2088123412341234");
            model.setBillType("trade");
            model.setBillDate("2024-03-16");
            request.setBizModel(model);
            AlipayDataDataserviceBillDownloadurlQueryResponse response = alipayClient.execute(request);
            String getzfb =  response.getBillDownloadUrl();
            System.out.println("获取到的下载地址"+getzfb);

            URL url = null;
            InputStream fis = null;
            HttpURLConnection httpUrlConnection = null;
            BufferedReader reader = null;
            try {
                url = new URL(getzfb);
                httpUrlConnection = (HttpURLConnection) url.openConnection();
                httpUrlConnection.setConnectTimeout(5 * 1000);
                httpUrlConnection.setDoInput(true);
                httpUrlConnection.setDoOutput(true);
                httpUrlConnection.setUseCaches(false);
                httpUrlConnection.setRequestMethod("GET");
                httpUrlConnection.setRequestProperty("Charsert", "GBK");
                httpUrlConnection.connect();

                fis = httpUrlConnection.getInputStream();
                System.out.println("获取的线上文件是*****"+fis);
                byte[] buf = new byte[4096];
                UniversalDetector detector = new UniversalDetector(null);
                int nread;
                while ((nread = fis.read(buf)) > 0 && !detector.isDone()) {
                    detector.handleData(buf, 0, nread);
                }
                detector.dataEnd();

                String encoding = detector.getDetectedCharset();
                if (encoding != null) {
                    System.out.println("支付宝的编码 =============================== " + encoding);
                } else {
                    System.out.println("No encoding detected.");
                }

                detector.reset();




//                下载到本机桌面
//                int responseCode = httpUrlConnection.getResponseCode();
//                String outputFilePath = "C:\\Users\\wangz\\Desktop\\downloaded.zip";
//                if (responseCode == HttpURLConnection.HTTP_OK) {
//                    try (InputStream inputStream = httpUrlConnection.getInputStream();
//                         FileOutputStream outputStream = new FileOutputStream(outputFilePath)) {
//                        byte[] buffer = new byte[4096];
//                        int bytesRead;
//                        while ((bytesRead = inputStream.read(buffer)) != -1) {
//                            outputStream.write(buffer, 0, bytesRead);
//                        }
//                    }
//                }



                if (httpUrlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                    //reader = new BufferedReader("/");
                    //reader = new BufferedReader(new InputStreamReader(getClass().getClassLoader().getResourceAsStream("/20882312163638180156_20240316_业务明细.csv")));

                    reader = new BufferedReader(new InputStreamReader(httpUrlConnection.getInputStream(), "GBK"));
                    String line;
                    while ((line = reader.readLine()) != null) {
                        System.out.println("支付宝数据"+line);
                    }
                } else {
                    System.out.println("HTTP Request failed with response code: " + httpUrlConnection.getResponseCode());
                }

                String line;
                BufferedReader br = new BufferedReader(new InputStreamReader(fis, Charset.forName("GBK")));
                    List<String[]> rows = new ArrayList<>();

                    while ((line = br.readLine()) != null) {
                        // 处理每一行的数据
                        System.out.println("支付宝的解析数据*********"+line);
                    }
                    // 打印解析后的数据
                    for (String[] row : rows) {
                        for (String cell : row) {
                            System.out.print("111111111111111111111111111111111"+cell + "\t");
                        }
                        System.out.println();
                    }

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if(fis!=null) fis.close();
                    if(httpUrlConnection!=null) httpUrlConnection.disconnect();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }catch (AlipayApiException e){
            e.printStackTrace();
        }
        return null;
    }
}
